package com.arvinclub.model.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Random;

/**
 * Created by zxy on 2018/7/3.
 * 用于图片压缩
 */
public class BASE64DecodedMultipartFile implements MultipartFile
{
    private final byte[] IMGCONTENT;
    private final String HEADER;
    private static Random random = new Random();

    BASE64DecodedMultipartFile(byte[] imgContent, String header)
    {
        this.IMGCONTENT = imgContent;
        this.HEADER = header.split(";")[0];
    }

    public String getName()
    {
        return System.currentTimeMillis() + Math.random() + "." + HEADER.split("/")[1];
    }

    public String getOriginalFilename()
    {
        return System.currentTimeMillis() + random.nextInt(10000) + "." + HEADER.split("/")[1];
    }

    public String getContentType()
    {
        return HEADER.split(":")[1];
    }

    public boolean isEmpty()
    {
        return IMGCONTENT == null || IMGCONTENT.length == 0;
    }

    public long getSize()
    {
        return IMGCONTENT.length;
    }

    public byte[] getBytes()
    {
        return IMGCONTENT;
    }

    public InputStream getInputStream()
    {
        return new ByteArrayInputStream(IMGCONTENT);
    }

    public void transferTo(File dest) throws IOException, IllegalStateException
    {
        new FileOutputStream(dest).write(IMGCONTENT);
    }


}
